package com.woniu.thridpartyservice.controller;

import com.woniu.thridpartyservice.service.SendSms;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 短信业务
 */
@Controller
public class SMSController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    SendSms sendSms;

    @GetMapping("/send/{phone}")
    @ResponseBody
    public String sms(@PathVariable("phone") String phone) {
        //1.先看redis中是否有phone的验证码
        String code = stringRedisTemplate.opsForValue().get(phone);
        //2.没有验证码,则在redis中放一个验证码
        if (!StringUtils.isEmpty(code)) {
            return "验证码还未过期";
        }
        String uuid = UUID.randomUUID().toString().substring(0, 4);
        //验证码120秒过期
        stringRedisTemplate.opsForValue().set(phone, uuid, 120, TimeUnit.SECONDS);

        String tempLateCode = "SMS_189521270";

        HashMap<String, Object> map = new HashMap<>();

        map.put("code", uuid);

        boolean send = sendSms.send(phone, tempLateCode, map);
        if (send) {
            return "验证码发送成功,请查看手机";
        } else {
            return "验证码发送失败请确认手机号===>phone:" + phone;
        }
    }

    @GetMapping("/checkCode/{phone}/{code}")
    @ResponseBody
    public String checkCode(
            @PathVariable("code") String code,
            @PathVariable("phone") String phone) {
        if (code.isEmpty()) {
            return "验证码不能为空";
        }
        //验证redis中的code
        String codeInRedis = stringRedisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(codeInRedis)) {
            //redis中无code,可能是手机号填错,也可能是code过期
            return "验证码失效,请重新尝试,并检查手机号";
        }
        if (code.equals(codeInRedis)) {
            return "验证码正确,请去登录";
        }

        return codeInRedis;
    }
}
